package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.PasswordConstant;
import com.itheima.constant.StatusConstant;
import com.itheima.dto.EmployeePageQueryDto;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import com.itheima.result.PageResult;
import com.itheima.service.EmployeeService;
import com.itheima.utils.CurrentLoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee) {
        //1. 补全实体属性
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));//设置密码-加密
        employee.setStatus(StatusConstant.ENABLE); //启用

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employee.setCreateUser(CurrentLoginHelper.getCurrentId()); //当前登录员工ID
        employee.setUpdateUser(CurrentLoginHelper.getCurrentId()); //当前登录员工ID

        //2. 调用mapper, 保存数据
        employeeMapper.insert(employee);
    }


    @Override
    public PageResult page(EmployeePageQueryDto pageQueryDTO) {
        //1. 设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        //2. 执行查询
        List<Employee> employeeList = employeeMapper.list(pageQueryDTO);

        //3. 解析并封装结果
        Page<Employee> page = (Page<Employee>) employeeList;
        return new PageResult(page.getTotal(), page.getResult());
    }


    @Override
    public void enableOrDisable(Integer status, Integer id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(CurrentLoginHelper.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }


    @Override
    public Employee getById(Integer id) {
        return employeeMapper.getById(id);
    }

    @Override
    public void update(Employee employee) {
        //实体属性拷贝
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(CurrentLoginHelper.getCurrentId());

        employeeMapper.update(employee);
    }
}
